package com.bigshen.algorithm.hHeap.solution02FindMedianFromDataStream;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * 295. Find Median from Data Stream
 * Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
 *
 * For example,
 * [2,3,4], the median is 3
 *
 * [2,3], the median is (2 + 3) / 2 = 2.5
 *
 * Design a data structure that supports the following two operations:
 *
 * void addNum(int num) - Add a integer number from the data stream to the data structure.
 * double findMedian() - Return the median of all elements so far.
 *
 * Example:
 *
 * addNum(1)
 * addNum(2)
 * findMedian() -> 1.5
 * addNum(3)
 * findMedian() -> 2
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/find-median-from-data-stream
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class MedianFinder {

    PriorityQueue<Integer> maxHeap; // 最大堆，存储较小元素
    PriorityQueue<Integer> minHeap; // 最小堆，存储较大元素
    int tmp = 0; // 中位值，随着加入的数据变化
    /** initialize your data structure here. */
    public MedianFinder() {
        maxHeap = new PriorityQueue(new Comparator<Integer>() {
            public int compare(Integer num1, Integer num2) {
                return num2 - num1;
            }
        });
        minHeap = new PriorityQueue();
    }

    public void addNum(int num) {
        if (maxHeap.size() == 0 && minHeap.size() == 0) {
            maxHeap.offer(num);
            tmp = num;
            return;
        }
        if (num > tmp) {
            minHeap.offer(num);
        } else {
            maxHeap.offer(num);
        }
        if (Math.abs(maxHeap.size()-minHeap.size()) > 1) {
            if (maxHeap.size() > minHeap.size()) {
                tmp = maxHeap.poll();
                minHeap.offer(tmp);
            } else {
                tmp = minHeap.poll();
                maxHeap.offer(tmp);
            }
        }
    }

    public double findMedian() {
        if (maxHeap.size() == minHeap.size()) {
            return Double.valueOf(maxHeap.peek()+minHeap.peek())/2;
        } else if (maxHeap.size() > minHeap.size()) {
            return maxHeap.peek();
        } else {
            return minHeap.peek();
        }
    }
}

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder obj = new MedianFinder();
 * obj.addNum(num);
 * double param_2 = obj.findMedian();
 */
